import json
import os
from typing import Dict, Any, Optional
from utils.logger import get_logger


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_path: str = "config.json"):
        self.config_path = config_path
        self.logger = get_logger("ConfigManager")
        self._config = {}
        self.load_config()
    
    def load_config(self) -> bool:
        """加载配置文件"""
        try:
            if os.path.exists(self.config_path):
                with open(self.config_path, 'r', encoding='utf-8') as f:
                    self._config = json.load(f)
                self.logger.info(f"成功加载配置文件: {self.config_path}")
                return True
            else:
                self.logger.warning(f"配置文件不存在: {self.config_path}")
                self._create_default_config()
                return False
        except Exception as e:
            self.logger.error(f"加载配置文件失败: {e}")
            self._create_default_config()
            return False
    
    def save_config(self) -> bool:
        """保存配置文件"""
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                json.dump(self._config, f, indent=4, ensure_ascii=False)
            self.logger.info(f"成功保存配置文件: {self.config_path}")
            return True
        except Exception as e:
            self.logger.error(f"保存配置文件失败: {e}")
            return False
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        value = self._config
        
        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default
    
    def set(self, key: str, value: Any) -> None:
        """设置配置值"""
        keys = key.split('.')
        config = self._config
        
        # 创建嵌套字典结构
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        config[keys[-1]] = value
        self.logger.info(f"设置配置项: {key} = {value}")
    
    def _create_default_config(self):
        """创建默认配置"""
        self._config = {
            "gitee": {
                "access_token": "",
                "base_url": "https://gitee.com/api/v5",
                "default_branch": "master"
            },
            "app": {
                "window_title": "Gitee仓库批量管理工具",
                "window_size": "900x700",
                "theme": "superhero"
            },
            "logging": {
                "level": "INFO",
                "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            }
        }
        self.save_config()
    
    @property
    def config(self) -> Dict[str, Any]:
        """获取完整配置字典"""
        return self._config.copy()


# 创建全局配置管理器实例
config_manager = ConfigManager("config.json")